using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.suppliers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.suppliers
{
    /// <summary>
    /// 添加供应商命令处理器
    /// </summary>
    public class AddSupplierCommandHandler : IRequestHandler<AddSupplierCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddSupplierCommandHandler> _logger;

        public AddSupplierCommandHandler(
            IBaseRepository<Supplier> supplierRepository,
            IMapper mapper,
            ILogger<AddSupplierCommandHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理添加供应商命令
        /// </summary>
        /// <param name="request">添加供应商命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(AddSupplierCommand request, CancellationToken cancellationToken)
        {
            try
            {

                // 验证供应商名称是否已存在
                var existingSupplierByName = await _supplierRepository.GetAll()
                    .FirstOrDefaultAsync(s => s.SupplierName == request.SupplierName && !s.IsDeleted, cancellationToken);

                if (existingSupplierByName != null)
                {
                    return ApiResult<int>.Error("供应商名称已存在，请使用其他名称");
                }

                // 使用AutoMapper将Command映射为实体
                var supplier = _mapper.Map<Supplier>(request);

                // 自动生成供应商编号：GYS + 当前时间（yyyyMMddHHmmss）
                supplier.SupplierCode = GenerateSupplierCode();
                supplier.CreatedTime = DateTime.Now;
                supplier.CreatedBy = request.CreatedBy;

                // 添加供应商
                var result = await _supplierRepository.AddAsync(supplier);

                if (result > 0)
                {
                    _logger.LogInformation("成功添加供应商，ID: {SupplierId}, 编号: {SupplierCode}, 名称: {SupplierName}", 
                        supplier.Id, supplier.SupplierCode, supplier.SupplierName);
                    
                    return ApiResult<int>.Success(supplier.Id, "供应商添加成功");
                }
                else
                {
                    _logger.LogError("添加供应商失败，编号: {SupplierCode}, 名称: {SupplierName}", 
                        supplier.SupplierCode, request.SupplierName);
                    
                    return ApiResult<int>.Error("供应商添加失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加供应商时发生异常，名称: {SupplierName}", 
                    request.SupplierName);
                
                return ApiResult<int>.Error($"添加供应商时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成供应商编号
        /// 格式：GYS + yyyyMMddHHmmss + 3位随机数
        /// </summary>
        /// <returns>供应商编号</returns>
        private string GenerateSupplierCode()
        {
            var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            var random = new Random().Next(100, 999); // 3位随机数，确保唯一性
            return $"GYS{timestamp}{random}";
        }
    }
}